/**
 * Project Name:九色鹿
 * File Name:UserSalesmanController.java
 * Package Name:com.fxp.project.jiuselu.web.business.v1.controller.user
 * Date:2021年09月15日 14:25
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.business.v1.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.rsa.RsaUtil;
import com.fxp.project.jiuselu.security.util.JwtTokenUtil;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.pojo.UserInfoVo;
import com.fxp.project.jiuselu.web.config.CustomerApiConfig;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.user.entity.JslSaleInfo;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.request.ReqLogin;
import com.fxp.project.jiuselu.web.models.user.request.ReqRegSalesMan;
import com.fxp.project.jiuselu.web.models.user.service.IJslSaleInfoService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import com.fxp.project.jiuselu.web.security.userdetails.CustomerUserDetails;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:UserSalesmanController<br/>
 * Function: 业务员<br/>
 * Date:2021年09月15日 14:25<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK 8
 */
@RestController
@RequestMapping("/v1/user/sales")
public class UserSalesmanController extends BaseController {

    @Autowired
    IJslUserService jslUserService;
    @Autowired
    IJslSaleInfoService jslSaleInfoService;
    @Autowired
    CustomerApiConfig customerApiConfig;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UserDetailsService userDetailsService;


    /**
     * apply: 申请成为业务员<br/>
     *
     * @param reqRegSalesMan
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/9/15 14:57
     */
    @PostMapping("apply")
    @CrossOrigin
    public CommonResult apply(@RequestBody @Validated ReqRegSalesMan reqRegSalesMan, BindingResult result) {
        super.checkBindResult(result);
        return jslSaleInfoService.saveOrUpdateToApply(super.getCurrentUserInfo().getUserId(), reqRegSalesMan);
    }

    /**
     * 代理注册
     * @param reqRegSalesMan
     * @param result
     * @return
     */
    @PostMapping("salesman")
    @CrossOrigin
    public CommonResult salesman(@RequestBody @Validated ReqRegSalesMan reqRegSalesMan, BindingResult result){
        super.checkBindResult(result);
        return jslSaleInfoService.salesman(reqRegSalesMan);
    }

    /**
     * detail: 获取当前用户的业务员详细信息<br/>
     * @author Jason.Wang
     * @date 2021/9/15 15:18
     */
    @PostMapping("detail")
    @CrossOrigin
    public CommonResult detail(@RequestBody @Validated ReqBase reqBase, BindingResult result) {
        super.checkBindResult(result);
        JslSaleInfo jslSaleInfo = jslSaleInfoService.getByUserId(super.getCurrentUserInfo().getUserId());
        return CommonResult.success(jslSaleInfo);
    }

    /**
     * invite: 查询当前销售员邀请的所有人信息<br/>
     *
     * @param reqBase
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/5 14:58
     */
    @PostMapping("invite")
    @CrossOrigin
    public CommonResult invite(@RequestBody @Validated ReqBase reqBase, BindingResult result) {
        super.checkBindResult(result);
        List<UserInfoVo> userInfoVoList = jslUserService.getUserInfoVoListByInviteId(super.getCurrentUserInfo().getUserId());
        return CommonResult.success(userInfoVoList);
    }

    /**
     * 代理登录
     * @return
     */
    @PostMapping("login")
    @CrossOrigin
    public CommonResult login(@RequestBody @Validated ReqLogin reqLogin, BindingResult result) {
        super.checkBindResult(result);
        // 当前对象为手机号+验证码、手机号+密码登录时需要检查当前用户是否存在
        // 当前账户采用验证码登录
        JslUser jslUser=null;
        if (reqLogin.getType() == 1) {
            if (!super.validMobileCode(reqLogin.getMobile(), reqLogin.getCode()))
            {
                return CommonResult.validateFailed("验证码错误");
            }
        } else if (reqLogin.getType() == 2) {
            jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone,reqLogin.getMobile()).eq(JslUser::getLevel,1));

            if (null == jslUser) {
                return CommonResult.failed("手机号未注册");
            }
            // 当前位手机号+ 密码登录方式
            String userPassword = null;
            String oldPasswork=null;
            try {
                userPassword = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(reqLogin.getPassword()),
                        customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (!passwordEncoder.matches(passwordEncoder.encode(userPassword),jslUser.getPassword())) {
                return CommonResult.failed("密码不正确");
            }
        }

//                if (null != userDetails.getJslUser() && 1 == userDetails.getJslUser().getIsLock()) {
//                    return CommonResult.failed("当前用户被锁定");
//                }


        JslSaleInfo jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getSalePhone, reqLogin.getMobile()));

        if (jslSaleInfo==null){
            return new CommonResult(503, "账户未存在，请先注册代理人", null);
        }

        switch (jslSaleInfo.getStatus()){
            case 0:
                return new CommonResult(501, "账户审核中", null);
            case 2:
                String remark=jslSaleInfo.getRemark()==null?"":jslSaleInfo.getRemark();
                return new CommonResult(502, "账户审核失败，请重新提交,失败理由："+remark, null);
        }

        CustomerUserDetails userDetails =
                (CustomerUserDetails) userDetailsService.loadUserByUsername(reqLogin.getMobile()+","+reqLogin.getStatus());
        //这里的认证信息应该是加密之前的。

        if (userDetails.getJslUser()==null&&reqLogin.getStatus()==1){
            return CommonResult.failed("数据问题");
        }

        UsernamePasswordAuthenticationToken upToken =
                new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
//        String b = jslUserService.checkPhone(reqLogin.getMobile());

        JslUser one = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqLogin.getMobile()).eq(JslUser::getLevel, 1));
        Long b=one.getInviteId();

        String invite = "";
        if (b == null) {
            invite = "false";
        } else {
            invite = "true";
        }
        Map<String, String> data = new HashMap<>();
        data.put("token", jwtTokenUtil.generateToken(userDetails));
        data.put("userId", super.getCurrentUserInfo().getUserId().toString());
        data.put("invite", invite);
        //状态更改为在线
        one.setUserId(super.getCurrentUserInfo().getUserId());
        one.setOnline(1);
        jslUserService.updateById(one);
        return CommonResult.success(data);
    }
}
